package me.yidasanqian.crowdfunding.service.impl;

import me.yidasanqian.crowdfunding.domain.Media;
import me.yidasanqian.crowdfunding.domain.User;
import me.yidasanqian.crowdfunding.domain.UserAuthc;
import me.yidasanqian.crowdfunding.mapper.MediaMapper;
import me.yidasanqian.crowdfunding.mapper.UserAuthcMapper;
import me.yidasanqian.crowdfunding.mapper.UserMapper;
import me.yidasanqian.crowdfunding.service.IUserAuthcService;
import me.yidasanqian.crowdfunding.util.PasswordHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author Linyu Chen
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserAuthcService implements IUserAuthcService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private UserAuthcMapper userAuthcMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private MediaMapper mediaMapper;

    @Override
    public String getIdentifier(String identifier) {
        return userAuthcMapper.getIdentifier(identifier);
    }

    @Override
    public void save(UserAuthc userAuthc) {
        userAuthcMapper.insert(userAuthc);
    }

    @Override
    public UserAuthc getUserAuthc(String username, String password) {
        return userAuthcMapper.getUserAuthc(username, password);
    }

    @Override
    public UserAuthc getUserAuthc(String username) {
        return userAuthcMapper.getUserAuthcByIdentifier(username);
    }

    @Override
    public void registerUser(UserAuthc userAuthc, String defaultAvatarUrl) {
        try {
            // 密码加密
            PasswordHelper.encryptPassword(userAuthc);
            save(userAuthc);
            Media media = new Media();
            media.setTitle("默认用户头像");
            media.setMediaType(0);
            media.setUrl(defaultAvatarUrl);
            mediaMapper.insert(media);
            logger.info("mediaId : " + media.getId());
            User user = new User();
            Date time = new Date();
            user.setUserAuthcId(userAuthc.getId());
            user.setTelephone(userAuthc.getIdentifier());
            user.setNickname("众筹用户" + time.getTime());
            user.setMedia(media);
            userMapper.insert(user);
        } catch (Exception e) {
            logger.error("registerUser 事务回滚 e : " + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
    }
}
